package com.ruoyi.goods.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.goods.domain.GoodsEntity;
import com.ruoyi.goods.service.ITbGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/goods")
public class TbGoodsController extends BaseController {

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.secretAccessKey}")
    private String secretAccessKey;

    @Autowired
    private ITbGoodsService tbGoodsService;

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) throws Exception {
        // 获取文件名
        String filename = file.getOriginalFilename();
        // 获取文件拓展名（包左不包右）
        String extName = filename.substring(filename.lastIndexOf("."));
        // 生成新的文件名
        String uuid = UUID.randomUUID().toString();
        String newFileName = uuid + extName;


        // 获取上传文件的流数据
        InputStream inputStream = file.getInputStream();

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider credentialsProvider =
                CredentialsProviderFactory.newDefaultCredentialProvider(accessKeyId,secretAccessKey);
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "bw2203a";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "goodsImage/" + newFileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String path = "https://bw2203a.oss-cn-beijing.aliyuncs.com/" + objectName;
        return success(path);
    }

    @PostMapping
    public AjaxResult save(@RequestBody GoodsEntity goodsEntity){
        tbGoodsService.save(goodsEntity);
        return AjaxResult.success();
    }
}
